package com.jaydenxiao.common.update;

import android.Manifest;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.jaydenxiao.common.R;

import org.json.JSONException;
import org.json.JSONObject;


/**
 * @author feicien (ithcheng@gmail.com)
 * @since 2016-07-05 19:21
 */
public class CheckUpdateTask extends AsyncTask<Void, Void, String> {

    private ProgressDialog dialog;
    private Activity mContext;
    private int mType;
    private String updateMessage, apkUrl;
    private String updateUrl = "";

    public CheckUpdateTask(Activity context, int type,String updateUrl) {

        this.mContext = context;
        this.mType = type;
        this.updateUrl=updateUrl;
    }


    protected void onPreExecute() {
//        if (mShowProgressDialog) {
//            dialog = new ProgressDialog(mContext);
//            dialog.setMessage(mContext.getString(R.string.android_auto_update_dialog_checking));
//            dialog.show();
//        }
    }


    @Override
    protected void onPostExecute(String result) {

//        if (dialog != null && dialog.isShowing()) {
//            dialog.dismiss();
//        }

        if (!TextUtils.isEmpty(result)) {
            parseJson(result);
        }
    }

    private void parseJson(String result) {
        try {

            JSONObject obj = new JSONObject(result);
            updateMessage = obj.getString(Constants.APK_UPDATE_CONTENT);
            apkUrl = obj.getString(Constants.APK_DOWNLOAD_URL);
            int apkCode = obj.getInt(Constants.APK_VERSION_CODE);

            int versionCode = AppUtils.getVersionCode(mContext);

            if (apkCode > versionCode) {
                Constants.versionIsNew=true;
                if (Build.VERSION.SDK_INT >= 26) {
                    boolean b = mContext.getPackageManager().canRequestPackageInstalls();
                    if (b) {
                        showVersionHint();
                    } else {
                        //请求安装未知应用来源的权限
                        ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 10010);
                        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                        mContext.startActivityForResult(intent, 10086);
                    }
                } else {
                    showVersionHint();
                }
            }

        } catch (JSONException e) {
            Log.e(Constants.TAG, "parse json error");
        }
    }


    public void showVersionHint() {
        if (mType == Constants.TYPE_NOTIFICATION) {
            showNotification(mContext, updateMessage, apkUrl);
        } else if (mType == Constants.TYPE_DIALOG) {
            showDialog(mContext, updateMessage, apkUrl);
        }
    }


    /**
     * Show dialog
     */
    private void showDialog(Activity context, String content, String apkUrl) {
        UpdateDialog.show(context, content, apkUrl);
    }

    /**
     * Show Notification
     */
    private void showNotification(Activity context, String content, String apkUrl) {
        Intent myIntent = new Intent(context, DownloadService.class);
        myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        myIntent.putExtra(Constants.APK_DOWNLOAD_URL, apkUrl);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = "updateChannelId";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, "自动更新", NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(channel);
        }
        int smallIcon = context.getApplicationInfo().icon;
        Notification notify = new NotificationCompat.Builder(context, channelId)
                .setTicker(context.getString(R.string.android_auto_update_notify_ticker))
                .setContentTitle(context.getString(R.string.android_auto_update_notify_content))
                .setContentText(content)
                .setSmallIcon(smallIcon)
                .setContentIntent(pendingIntent).build();
        notify.flags = Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, notify);
    }

    @Override
    protected String doInBackground(Void... args) {
        return HttpUtils.get(updateUrl);
    }



}
